package com.clippick.api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GetDataFromApi {

	public static final String SERVER = "http://clippick.com/mobile/";
	public static final String IMAGE_SERVER = "http://clippick.com";
	public static final String INVITE_URL = "http://www.clippick.com/u/create.php?u=http://clippick.com/sign_up_invite.php?id=";

	// server api
	public static final String API_DELETE = "delete_new.php";
	public static final String API_CHANGE = "change_new.php";
	public static final String API_GET_FEEDS = "getFeeds_new.php";
	public static final String API_INSERT_IMAGE = "insert_new.php";
	public static final String API_INSERT = "insert_new.php";
	public static final String API_SYNC_CHECK = "syncCheck_new.php";
	public static final String API_NODEJS_INSERT = ":3001/insert";
	public static final String API_NODEJS_LONG_POLLING = ":3000/update/";
	public static final String API_NODEJS_SIGN_UP = ":3001/signup";
	public static final String API_NODEJS_PING = ":3000/ping/";
	public static final String API_SYNC_CHECK_TIME = "syncCheck2_new.php";

	public static String TYPE = "GET";

	private final String[] nodeJSArray = { API_NODEJS_INSERT,
			API_NODEJS_LONG_POLLING, API_NODEJS_SIGN_UP, API_NODEJS_PING };

	public static List<Map> getData(String method, Map<String, String> params) {
		String rawString = "";
		rawString = getRaw(method, params);
		if (!rawString.equals("") && rawString != null)
			if (rawString.startsWith("{")) {
				if (rawString.indexOf("{\"returnType") != -1) {
					return parseJson(rawString, "Feeds");
				} else if (rawString.indexOf("[{") != -1) {
					return parseJson(rawString, "");
				} else {
					if (rawString != null && !rawString.equals("")) {
						List<Map> returnList = new ArrayList<Map>();
						Map m = new HashMap<String, String>();
						m.put("data", rawString);
						returnList.add(m);
						return returnList;
					}
				}
			}
		return null;
	}

	public static String getRaw(String method, Map<String, String> params) {
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		List<Map> returnList = new ArrayList<Map>();
		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		String jsonData = null;
		try {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				// Log.d("api", entry.getKey() + "=" + entry.getValue());
				postParams.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue()));
			}

			// GET
			if (TYPE.equals("GET")) {
				String tmpUrl = "";
				String tmpServer = SERVER + method;
				if (!tmpServer.endsWith("?")) {
					StringBuilder builder = new StringBuilder();
					tmpUrl = builder.append(tmpServer).append("?").toString();
				}
				String paramString = URLEncodedUtils
						.format(postParams, "utf-8");
				tmpUrl += paramString;
				HttpGet getReq = new HttpGet();
				getReq.setURI(new URI(tmpUrl));
				// Log.d("api", "uri=" + tmpUrl);
				response = client.execute(getReq);

			} else {
				HttpPost request = new HttpPost();

				if (method.equals(API_NODEJS_LONG_POLLING)
						|| method.equals(API_NODEJS_PING)
						|| method.equals(API_NODEJS_INSERT)
						|| method.equals(API_NODEJS_SIGN_UP)) {
					request.setURI(new URI(IMAGE_SERVER + method));
				} else {
					request.setURI(new URI(SERVER + method));
				}

				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(postParams,
						HTTP.UTF_8);
				request.setEntity(ent);
				response = client.execute(request);
			}

			BufferedReader in = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String tempStr;
			StringBuilder htmlSource = new StringBuilder();
			while ((tempStr = in.readLine()) != null) {
				htmlSource.append(tempStr);
			}
			in.close();
			// Log.d("api", "respons=" + htmlSource.toString());
			jsonData = htmlSource.toString();
		} catch (Exception e) {
			if (e != null) {
				e.printStackTrace();
			}
		} finally {
			client.getConnectionManager().shutdown();
		}

		// keep response for star data
		// if (jsonData.contains("\"Star_Count\":")) {
		// Log.i("global", GlobalValue.STAR_DATA_STR);
		// GlobalValue.STAR_DATA_STR = jsonData;
		// }

		return jsonData;
	}

	public static List<Map> parseJson(String jsonData, String keyName) {

		List<Map> results = new ArrayList<Map>();
		List<Map> returnList = new ArrayList<Map>();
		try {
			JSONArray jaArray;
			if (keyName.equals("")) {
				jaArray = new JSONArray(jsonData);
			} else {
				JSONObject ja = new JSONObject(jsonData);
				jaArray = ja.getJSONArray(keyName);
			}
			for (int i = 0; i < jaArray.length(); i++) {
				JSONObject order = jaArray.getJSONObject(i);
				Iterator itr = order.keys();
				Map m = new HashMap<String, String>();
				while (itr.hasNext()) {
					Object key = itr.next();
					// Log.d("api",
					// "\t key : " + key + " , value : "
					// + order.get((String) key));

					m.put(key, order.get((String) key));
				}
				returnList.add(m);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnList;
	}
}
